package net.ankao.job.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Optional;

/**
 * @author LILU
 * @date 2024-11-15 11:40
 */
public class NetworkUtil {

    /**
     * 获取第一个非回环和非链路本地的IPv4地址。
     * @return 返回一个Optional对象，包含找到的第一个IPv4地址，如果没有找到合适的IP则返回空。
     */
    public static Optional<String> getLocalIPv4Address() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();

                for (Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                     inetAddresses.hasMoreElements();) {

                    InetAddress inetAddress = inetAddresses.nextElement();

                    // 忽略回环地址和链路本地地址
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
                        // 只处理IPv4地址
                        if (inetAddress instanceof java.net.Inet4Address) {
                            return Optional.of(inetAddress.getHostAddress());
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        // 如果没有找到合适的IP地址，则返回空的Optional
        return Optional.empty();
    }

}
